package com.lmx.web.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.froala.editor.Image;
import com.lmx.common.util.CommonUtil;
import com.lmx.common.util.URLUtil;

/**
 * 富文本编辑器的图片/文件上传
 *
 * @author ytche
 * @date 2017年6月24日
 *
 */
@Controller
@RequestMapping
public class EditorFileUploadController {
	private static Log logger = LogFactory
			.getLog(EditorFileUploadController.class);

	@ResponseBody
	@RequestMapping(method = { RequestMethod.PUT, RequestMethod.POST }, value = "/image/editor")
	public void uploadImage(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("Content-Type") String contentType,
			@RequestParam("businessType") String businessType) {
		String savePath = URLUtil.getInstance().getSaveDirPath(contentType,
				businessType);
		logger.debug("contentType : " + contentType);
		logger.debug("businessType : " + businessType);
		Map<Object, Object> responseData;
		try {
			responseData = Image.upload(request, savePath); // Use default
		} catch (Exception e) {
			logger.error(e);
			responseData = new HashMap<Object, Object>();
			responseData.put("error", e.toString());
		}
		String link = (String) responseData.get("link");
		link = link.replace(URLUtil.getInstance().getRootDir()
				+ URLUtil.getInstance().getFileTypeDir(contentType)
				+ URLUtil.getInstance().getBusinessTypeDir(businessType), "");
		link = URLUtil.getInstance().getImgServerUrl() + "/" + businessType
				+ "/" + link;
		responseData.put("link", link);
		String jsonResponseData = CommonUtil.mapToJsonString(responseData);

		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		try {
			response.getWriter().write(jsonResponseData);
		} catch (IOException e) {
			logger.debug("返回response出错", e);
		}
	};
}
